﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Emgu.CV;

namespace isDrone
{
    public partial class VideoControl : UserControl
    {

        private Size size = new Size(640, 480);
        private Size size1;
        
        public VideoControl()
        {
            InitializeComponent();
         SetStyle(ControlStyles.DoubleBuffer |
   ControlStyles.UserPaint |
   ControlStyles.AllPaintingInWmPaint,
   true);
            this.UpdateStyles();
        }

        private void pictureBox1_Resize(object sender, EventArgs e)
        {
             
               
                      size = pictureBox1.ClientSize;
                 
                 
             }

        public void SetImage(Bitmap bitmap)
        {

              try
                {
                Image<Emgu.CV.Structure.Bgr, byte> image = new Image<Emgu.CV.Structure.Bgr, byte>(bitmap);
                SetImage(image);
                image.Dispose();
                }
              catch
              {
                 
              }
           
        }
        [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions()]
        public void SetImage(Image<Emgu.CV.Structure.Bgr, byte> image)
        {
           
            double k = 1;
            lock (ov)
            {
                double kw = Convert.ToDouble(image.Width)/size.Width;
                double kh = Convert.ToDouble(image.Height)/size.Height;
                 k = Math.Max(kw, kh);
          
                var resize = image.Resize(1/k, Emgu.CV.CvEnum.INTER.CV_INTER_LINEAR);
           
                ShowImage(resize.Bitmap);
            
            resize.Dispose();  
            }
        }

        delegate void ShowImageCallback(Bitmap bitmap);

        private object ov = new object();
        private void ShowImage(Bitmap bitmap)
        {
            if (pictureBox1.InvokeRequired)
            {
                ShowImageCallback d = ShowImage;
                Invoke(d, bitmap);
            }
            else
            {
                try
                { 
                pictureBox1.Image = bitmap;
                pictureBox1.Refresh();
                
                 }
            catch
            {
                pictureBox1 = new PictureBox();
                pictureBox1.Resize += pictureBox1_Resize;
                pictureBox1.Dock = DockStyle.Fill;
                pictureBox1.Parent = this;
                pictureBox1.SizeMode = PictureBoxSizeMode.CenterImage;
            }
            }
        }

        private void pictureBox1_Paint(object sender, PaintEventArgs e)
        {

        }
    }
}
